/*
 * @FilePath: /tads/server/common/auth/auth.go
 * @Author: wnina0x0
 * @Date: 2025-04-29 11:42:04
 * @Description:
 *
 * 版权信息 : 2025 by wnina0x0, All Rights Reserved.
 */
package auth

import (
	"errors"
	"net/http"
	"strings"
	"tads/server/global"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		CheckJwt(authHeader, c, global.TADS_PARSER_OPTION)

	}
}
func CheckJwt(authorization string, c *gin.Context, options ...jwt.ParserOption) {
	if strings.Compare(authorization, "") == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 401,
			"msg":  "无登陆信息，请登陆",
		})
		c.Abort()
		return
	}
	token, err := jwt.Parse(authorization, func(token *jwt.Token) (interface{}, error) {
		return global.TADS_AUTH_KEY, nil
	}, options...)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 401,
			"msg":  err.Error(),
		})
		c.Abort()
		return
	}
	// 校验 Claims 对象是否有效，基于 exp（过期时间），nbf（不早于），iat（签发时间）等进行判断（如果有这些声明的话）。
	if !token.Valid {
		c.JSON(http.StatusOK, gin.H{
			"code": 401,
			"msg":  errors.New("invalid token"),
		})
		c.Abort()
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success!",
	})
	c.Next()

}
